<template>
  <je-modal
    v-model:visible="visibleModule"
    width="600px"
    height="auto"
    class="matrix-config"
    :resize="false"
    :maximizable="false"
    title="按矩阵处理"
    cancel-button
    :ok-button="addModule"
    @close="cancelModal"
  >
    <je-form layout="vertical" autocomplete="off" :model="formState">
      <Row gutter="16">
        <Col span="12">
          <je-form-item name="matrixName" v-bind="validateInfos.matrixName" label="矩阵名称">
            <je-select-grid
              v-model:value="formState.matrixName"
              :model="formState"
              config-info="JE_RBAC_MATRIX,matrixName~matrixId,MATRIX_JZMC~JE_RBAC_MATRIX_ID,S"
              :querys="[{ code: 'MATRIX_SFJY', type: '!=', value: '1' }]"
            />
          </je-form-item>
        </Col>
        <Col span="12">
          <je-form-item name="sql" label="结果字段">
            <je-input v-model:value.trim="formState.resultField" disabled />
          </je-form-item>
        </Col>
      </Row>
    </je-form>
    <Grid
      ref="$grid"
      border
      auto-resize
      show-overflow="ellipsis"
      keep-source
      show-header-overflow
      class="matrix-config-grid"
      resizable
      height="300"
      size="mini"
      header-align="center"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showStatus: true,
      }"
      :store="gridStore"
    >
      <GridColumn width="40" :align="center">
        <template #header>
          <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
        </template>
        <template #default="{ row }">
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-times"
            @click="deleteColumn(row)"
          ></i>
        </template>
      </GridColumn>
      <GridColumn field="condition" title="条件字段" width="260" :edit-render="inputRender">
        <template #edit="{ row }">
          <je-select
            v-model:value="row.condition"
            :get-popup-container="getPopupContainer"
            :options="conditionOptions"
          />
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.condition, conditionOptions) }}
        </template>
      </GridColumn>
      <GridColumn field="conditionValue" title="条件值" width="auto" :edit-render="inputRender">
        <template #edit="{ row }">
          <je-select-grid
            v-model:value="row.conditionValue"
            config-info="JE_CORE_RESOURCEFIELD,conditionValue,RESOURCEFIELD_CODE,M"
            :querys="[
              { code: 'RESOURCEFIELD_FUNCINFO_ID', type: '=', value: funcInfo.funcId, cn: 'and' },
              {
                code: 'RESOURCEFIELD_XTYPE',
                type: 'notIn',
                value: ['fieldset', 'child', 'childfuncfield', 'displayfield'],
                cn: 'and',
              },
            ]"
            editable
            @select="doSelectConditionValue"
          />
        </template>
      </GridColumn>
    </Grid>
  </je-modal>
</template>
<script>
  import { defineComponent, ref, reactive, watch } from 'vue';
  import { Input, Modal, Form, Row, Col, Grid, Data, InputSelect } from '@jecloud/ui';
  import { verifyData } from '@/helper/common';
  import { inputRender } from '@/helper/edit-render';
  import { getData } from '@/api/index';
  import { encode, decode, isNotEmpty, cloneDeep } from '@jecloud/utils';

  const useForm = Form.useForm;
  export default defineComponent({
    name: 'MatrixConfig',
    components: {
      JeModal: Modal,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      Row,
      Col,
      Grid: Grid,
      GridColumn: Grid.Column,
      JeSelectGrid: InputSelect.Grid,
    },
    props: {
      checkedRow: {
        type: Object,
        default: () => {
          return {};
        },
      },
      funcInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    emits: ['setModalType', 'closeModal'],
    setup(props, { emit }) {
      const $grid = ref();
      const gridStore = Data.Store.useGridStore({
        data: [],
      });
      const conditionOptions = ref([]);
      //保存模块数据，关闭弹窗
      const visibleModule = ref(true);
      const formState = reactive({
        matrixName: props.checkedRow.resourceName || '',
        matrixId: props.checkedRow.config?.matrixId || '',
        resultField: props.checkedRow.config?.resultField || '',
        resultFieldId: props.checkedRow.config?.resultFieldId || '',
        gridData: props.checkedRow.config?.gridData || '',
      });
      const loadType = ref(false);
      if (isNotEmpty(formState.gridData)) {
        gridStore.loadData(decode(formState.gridData));
      }

      const rulesRef = reactive({
        matrixName: [verifyData.required],
      });
      const { resetFields, validate, validateInfos } = useForm(formState, rulesRef, {
        onValidate: (...args) => {},
      });
      const validRules = ref({
        condition: [verifyData.required],
        conditionValue: [verifyData.required],
      });
      const addModule = ({ $modal, button }) => {
        const gridData = [];
        gridStore.data.forEach((item) => {
          if (isNotEmpty(item.condition) && isNotEmpty(item.conditionValue)) {
            gridData.push(item);
          }
        });
        if (gridData.length <= 0) {
          Modal.alert('列表数据或字段不能为空！', 'warning');
        } else {
          //保存数据逻辑
          validate()
            .then(() => {
              formState.gridData = encode(gridData);
              emit('setModalType', { type: 'matrixConfig', data: formState });
              emit('closeModal', { type: 'ok', modalType: 'matrixConfig' });
              $modal.close();
            })
            .catch((error) => {});
        }

        return false;
      };
      //弹窗关闭方法
      const cancelModal = () => {
        emit('closeModal', { type: 'cancel', modalType: 'matrixConfig' });
      };

      // 添加列
      const addColumn = () => {
        const data = {
          condition: '',
          conditionValue: '',
        };
        gridStore.insert(data, -1);
      };
      // 删除列
      const deleteColumn = (row) => {
        gridStore.remove(row);
      };
      //
      const getMatrixField = () => {
        if (loadType.value) {
          gridStore.loadData([]);
        }

        conditionOptions.value = [];
        formState.resultField = '';
        getData(
          {
            tableCode: 'JE_RBAC_MATRIX_FIELD',
            funcCode: 'JE_RBAC_MATRIX_FIELD',
            j_query: encode([
              {
                code: 'JE_RBAC_MATRIX_ID',
                type: '=',
                value: formState.matrixId,
                cn: 'and',
              },
            ]),
          },
          { pd: 'rbac' },
        ).then((data) => {
          if (data && data.rows.length > 0) {
            data.rows.forEach((item) => {
              // 条件字段
              if (item.FIELD_ZDLX_CODE == 'condition') {
                conditionOptions.value.push({
                  label: item.FIELD_ZDMC,
                  value: item.JE_RBAC_MATRIX_FIELD_ID,
                });
              }
              // 结果字段
              if (item.FIELD_ZDLX_CODE == 'result') {
                formState.resultField = item.FIELD_ZDMC;
                formState.resultFieldId = item.JE_RBAC_MATRIX_FIELD_ID;
              }
            });
            loadType.value = true;
            updateSelectOption();
          }
        });
      };
      const doSelectConditionValue = ({ rows }) => {
        if (rows && rows.length > 0) {
          rows[0].RESOURCEFIELD_CODE = `{${rows[0].RESOURCEFIELD_CODE}}`;
        }
      };

      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };
      //
      const updateSelectOption = () => {
        const conditionDatas = [];
        const newOptions = [];
        gridStore.data.forEach((item) => {
          conditionDatas.push(item.condition);
        });
        conditionOptions.value.forEach((val) => {
          if (conditionDatas.includes(val.value)) {
            val.disabled = true;
          } else {
            val.disabled = false;
          }
          newOptions.push(val);
        });
      };

      watch(
        () => formState.matrixId,
        () => {
          getMatrixField();
        },
        { immediate: true },
      );
      watch(
        () => gridStore.data,
        () => {
          updateSelectOption();
        },
        { deep: true },
      );

      const getPopupContainer = () => {
        return document.body;
      };
      return {
        addModule,
        visibleModule,
        formState,
        cancelModal,
        validateInfos,
        resetFields,
        addColumn,
        deleteColumn,
        getPopupContainer,
        conditionOptions,
        inputRender,
        gridStore,
        doSelectConditionValue,
        getSelectLabel,
        validRules,
        $grid,
      };
    },
  });
</script>

<style lang="less" scoped>
  .matrix-config {
    .matrix-config-grid {
      margin-top: 15px;
    }
  }
</style>
